<?php

namespace App\Service\UserService\SubUserRouterService;
use Service\BaseService;
use App\Service\Code\Normal;
use App\Model\PssModel\PddToken;
use App\Service\VendorClient\PddApi\ShopPddUserApiClient;
use App\Model\PssModel\OrderPullLog;

/**
 * 多多三方渠道配置逻辑
 * @author 
 */
class Pdd extends BaseService
{
    /**
     * 获取新增多多渠道用户需要组装参数模板数据
     */
    public function getAddUserData(array $param)
    {
        if (!$param['isNeedCreateChannel']) {
            return Normal::returnCode(Normal::SUC,"不需要获取Pdd参数",[]);
        }

        if( empty($param['extends']) ) {
            return Normal::returnCode(Normal::FAIL,"extends不能为空!");
        }

        $extends = $param['extends'];
        $rule = [
            "shopID"            => '拼多多店铺ID',
            "ownerUserName"     => '关务货主名称',
            "linkUserName"      => '联系人姓名',
            "linkUserPhone"     => '联系人电话',
            "wareHouseList"     => '拼多多商品关区明细',
            "sendUserName"      => '发货人姓名',
            "sendUserPhone"     => '发货人电话',
            "sendProvince"      => '发货省份',
            "sendCity"          => '发货城市',
            "sendDistinct"      => '发货区/县',
            "sendDetailAddress" => '发货详细地址',
            "templateUrl"       => '多多面单物流公司地址',
            "wpCode"            => '多多面单物流公司编码',
        ];
        foreach ($rule as $key => $value ) {
            if( !array_key_exists($key,$extends) ) {
                return Normal::returnCode(Normal::FAIL,"请求参数【{$key}】缺失");
            }
        }

        $wareHouseList = [];
        //校验多多关区(目前不校验)
//        $wareHouseList = array_filter(array_unique($extends['wareHouseList']));
//        if( empty($wareHouseList) ) {
//            return Normal::returnCode(Normal::FAIL,"请求参数extends.wareHouseList不合法，请按照格式:['A','B']进行处理! ");
//        }

        $wareHouseList[] = $extends['wareHouseList'];
        
        //组装参数
        $_return = [
            'bonded_warehouse_list' => $wareHouseList,
            'payCompanyInfo'        => [
                [

                    "payType"           => "WEIXIN",
                    "payCommanyName"    => "财付通支付科技有限公司",
                    "payCommanyCode"    => "4403169D3W"
                ],
                [

                    "payType"           => "QQ",
                    "payCommanyName"    => "财付通支付科技有限公司",
                    "payCommanyCode"    => "4403169D3W"
                ],
                [

                    "payType"           => "ALIPAY",
                    "payCommanyName"    => "支付宝(中国)网络技术有限公司",
                    "payCommanyCode"    => "31222699S7"
                ],
                [

                    "payType"           => "DUODUOPAY",
                    "payCommanyName"    => "上海付费通信息服务有限公司",
                    "payCommanyCode"    => "310598007D"
                ],
            ],
            'enterCompanyInfo'  => [
                'enterpriseNum'     => '3105961682',
                'enterpriseName'    => '上海寻梦信息技术有限公司'
            ],
            'senderUserInfo'    => [
                'address'   => [
                    "city"      => $extends['sendCity'],
                    "detail"    => $extends['sendDetailAddress'],
                    "district"  => $extends['sendDistinct'],
                    "province"  => $extends['sendProvince']
                ],
                "mobile"    => $extends['linkUserPhone'],
                "name"      => $extends['linkUserName'],
                "phone"     => $extends['linkUserPhone']
            ],
            "template_url"      => $extends['templateUrl'],
            "wp_code"           => $extends['wpCode'],
            "interval_hours"    => 2,
            "start_date"        => "",
            "wayUserID"         => "187"
        ];
        
        if( !empty($extends['wayUserID']) ) {
            $_return['wayUserID'] = $extends['wayUserID'];
        }
        
        return Normal::returnCode(Normal::SUC,"获取成功",$_return);
    }
    
    /**
     * 重新获取捞单池的数据，店铺修改了收货信息
     * @param array $config
     * @param array $orderPullLog
     */
    public function ReGetUserOrder(array $config,array $orderPullLog)
    {
        if( empty($config['pdd_status']) ) {
            return Normal::returnCode(Normal::FAIL,"云仓系统-业务配置-订单捞单池异常状态配置未配置pdd_status状态范围!");
        }
        
        $pdd_status_arr = \explode(",",$config['pdd_status']);
        if( !in_array($orderPullLog['pdd_status'],$pdd_status_arr) )
        {
            return Normal::returnCode(Normal::FAIL,"捞单池需要重新获取订单的数据不满足需要捞取的状态");
        }
        
        if( in_array($orderPullLog['status'],[1,2,3]) ) {
            return Normal::returnCode(Normal::FAIL,"当前订单不满足，需要重新捞取的条件，订单已推送上游!");
        }
        
        
        $order_sn = $orderPullLog['order_sn'];
        $origin_order_info = json_decode($orderPullLog['contents'],true);
        $shop = PddToken::instance()->info(['bid'=>$orderPullLog['bid']]);
        $client = new ShopPddUserApiClient($shop);
        $result = $client->queryOrderDetail([
            'order_sn'  => $order_sn
        ]);
        
        if( $result['code'] != Normal::SUC ) {
            return $result;
        }
        
        //得到最新的订单报文
        $orderInfo = $result['data']['order_info_get_response']['order_info'];
        $origin_order_info['receiver_name']  = $orderInfo['receiver_name'];
        $origin_order_info['receiver_phone'] = $orderInfo['receiver_phone'];
        $origin_order_info['province']       = $orderInfo['province'];
        $origin_order_info['city']           = $orderInfo['city'];
        $origin_order_info['town']           = $orderInfo['town'];
        $origin_order_info['address']        = $orderInfo['address'];


        $new_update_arr = [];
        //重新获取新的电子面单
        $res = $client->getWaybill([$origin_order_info]);
        if( $res['code'] == Normal::SUC )
        {
            $waybill_info = $res['data'][$order_sn];
            $origin_order_info['waybill_info'] = [
                'print_code'    => 200,
                'print_msg'     => "获取面单成功",
                'print_data'    => $waybill_info['waybill_print_data'],
                'waybill_code'  => $waybill_info['waybill_code'],
                'wp_code'       => $waybill_info['object_id'],
            ];
            $new_update_arr['contents']       = json_encode($origin_order_info,JSON_UNESCAPED_UNICODE);
            $new_update_arr['response_msg']   = "电子面单获取成功";
            $new_update_arr['pdd_status']     = 0;
            //更新到待获取面单状态
            OrderPullLog::instance()->where('id',$orderPullLog['id'])->update($new_update_arr);
            return Normal::returnCode(Normal::SUC,"操作成功");
        }
        else 
        {
            //电子面单获取失败
            $errorMsg = isset($res['data']['error_response']['sub_msg']) ? $res['data']['error_response']['sub_msg'] : $res['msg'];
            $origin_order_info['waybill_info'] = [
                'print_code'    => 0,
                'print_msg'     => $errorMsg
            ];
            $new_update_arr['contents']       = json_encode($origin_order_info,JSON_UNESCAPED_UNICODE);
            $new_update_arr['response_msg']   = "电子面单获取失败【{$errorMsg}】";
            $new_update_arr['pdd_status']     = 2;
            //更新到待获取面单状态
            OrderPullLog::instance()->where('id',$orderPullLog['id'])->update($new_update_arr);
            return Normal::returnCode(Normal::FAIL,$new_update_arr['response_msg']);
        }
    }
}